/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * JEditorWarpDialog.java
 *
 * Created on 2010-10-4, 10:43:22
 */

package cn.ekuma.data.ui.swing;

import cn.ekuma.data.dao.I_DataLogic;
import cn.ekuma.data.dao.bean.I_BaseBean;
import com.openbravo.data.basic.BasicException;
import com.openbravo.data.gui.JMessageDialog;
import com.openbravo.data.gui.MessageInf;
import com.openbravo.data.user.DirtyListener;
import com.openbravo.data.user.DirtyManager;
import java.awt.Component;
import java.awt.Dialog;
import java.awt.Frame;
import java.awt.HeadlessException;
import java.awt.Window;
import java.util.Properties;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JDialog;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
import javax.swing.JComboBox;
import javax.swing.JButton;
import java.awt.Dimension;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.WindowListener;

import javax.swing.JPanel;
import java.awt.FlowLayout;

/**
 *
 * @author Administrator
 */
public class JEditorWarpDialog<T> extends javax.swing.JDialog implements SwingEditorRecord<T> {

    AbstractDAOJEditor<T> editor;
    I_DataLogic dlSales;
    protected DirtyManager dirty;
    protected T retObj;
  
    protected DefaultComboBoxModel cobeModel;


    public JEditorWarpDialog(Frame window, String string, boolean b) {
		super(window,string,b);
		
	}

	public JEditorWarpDialog(Dialog window, String string, boolean b) {
		super(window,string,b);
	}

	/** Creates new form JEditorWarpDialog */
    public JEditorWarpDialog<T> init(final I_DataLogic dlSale,final AbstractDAOJEditor<T> editor) {
        this.dlSales=dlSale;
        this.editor=editor;
        dirty=editor.getDirty();
        
        cobeModel=new DefaultComboBoxModel();
        initComponents();
        getContentPane().add(editor, java.awt.BorderLayout.CENTER);
        editor.configTotalPanel(extPanel);
        jhostCob.setModel(cobeModel);
        dirty.addDirtyListener(new DirtyListener(){
			@Override
			public void changedDirty(boolean bDirty) {
				if(dlSales!=null)
				    jButton1.setEnabled(bDirty);
				m_jButtonOK.setEnabled(bDirty);	
			}
        });
        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-this.getWidth())/2, (screenSize.height-this.getHeight())/2, getWidth(), getHeight());
        this.pack();
        return this;
    }

    public static JEditorWarpDialog getInstance(Component parent){
    	JEditorWarpDialog dialog;
    	Window window = JEditorWarpDialog.getWindowForComponent(parent);
        if (window instanceof Frame) {
            dialog = new JEditorWarpDialog((Frame)window, "对象编辑", true);
        } else {
            dialog = new JEditorWarpDialog((Dialog)window, "对象编辑", true);
        }
      return dialog;
    }
    
    
    /**
     * Returns the specified component's toplevel <code>Frame</code> or
     * <code>Dialog</code>.
     *
     * @param parentComponent the <code>Component</code> to check for a
     *          <code>Frame</code> or <code>Dialog</code>
     * @return the <code>Frame</code> or <code>Dialog</code> that
     *          contains the component, or the default
     *          frame if the component is <code>null</code>,
     *          or does not have a valid
     *          <code>Frame</code> or <code>Dialog</code> parent
     * @exception HeadlessException if
     *   <code>GraphicsEnvironment.isHeadless</code> returns
     *   <code>true</code>
     * @see java.awt.GraphicsEnvironment#isHeadless
     */
    static Window getWindowForComponent(Component parentComponent)
        throws HeadlessException {
        if (parentComponent == null)
            return JOptionPane.getRootFrame();
        if (parentComponent instanceof Frame || parentComponent instanceof Dialog)
            return (Window)parentComponent;
        return JEditorWarpDialog.getWindowForComponent(parentComponent.getParent());
    }
 
    
    
    public void refresh() {
        editor.refresh();
    }

    public void writeValueDelete(T value) {
    	retObj=null;
    	dirty.setDirty(false);
        editor.writeValueDelete(value);
        setVisible(true);
    }

    public void writeValueEOF() {
    	retObj=null;
    	dirty.setDirty(false);
        editor.writeValueEOF();
        setVisible(true);
    }

    public void writeValueEdit(T value) {
    	retObj=null;
    	dirty.setDirty(false);
        editor.writeValueEdit(value);
        setVisible(true);
    }

    public void writeValueInsert(Properties prop) {
    	retObj=null;
    	dirty.setDirty(false);
        editor.writeValueInsert(prop);
        setVisible(true);
    }
    
    public void writeValueInsert(T prop) {
    	retObj=null;
    	dirty.setDirty(false);
        editor.writeValueInsert(new Properties());
        editor.hostSelected(prop);
        setVisible(true);
    }

    public T createValue() throws BasicException {
        return editor.createValue();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel5 = new javax.swing.JPanel();
        jButton1 = new javax.swing.JButton();
        m_jButtonOK = new javax.swing.JButton();
        m_jButtonCancel = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jPanel5.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.RIGHT));

        jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/openbravo/images/filesave.png"))); // NOI18N
        jButton1.setMargin(new java.awt.Insets(8, 16, 8, 16));
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });
        
        extPanel = new JPanel();
        FlowLayout fl_extPanel = (FlowLayout) extPanel.getLayout();
        fl_extPanel.setAlignment(FlowLayout.LEFT);
        jPanel5.add(extPanel);
        
        jhostCob = new JComboBox();
        jhostCob.setPreferredSize(new Dimension(200, 21));
        jhostCob.setMaximumRowCount(10);
        jPanel5.add(jhostCob);
        
        btnC = new JButton("C");
        btnC.addActionListener(new ActionListener() {
        	public void actionPerformed(ActionEvent e) {
        		cobeModel.removeAllElements();
        	}
        });
        jPanel5.add(btnC);
        jPanel5.add(jButton1);

        m_jButtonOK.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/openbravo/images/button_ok.png"))); // NOI18N
        m_jButtonOK.setFocusPainted(false);
        m_jButtonOK.setFocusable(false);
        m_jButtonOK.setMargin(new java.awt.Insets(8, 16, 8, 16));
        m_jButtonOK.setRequestFocusEnabled(false);
        m_jButtonOK.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                m_jButtonOKActionPerformed(evt);
            }
        });
        jPanel5.add(m_jButtonOK);

        m_jButtonCancel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/openbravo/images/button_cancel.png"))); // NOI18N
        m_jButtonCancel.setFocusPainted(false);
        m_jButtonCancel.setFocusable(false);
        m_jButtonCancel.setMargin(new java.awt.Insets(8, 16, 8, 16));
        m_jButtonCancel.setRequestFocusEnabled(false);
        m_jButtonCancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                m_jButtonCancelActionPerformed(evt);
            }
        });
        jPanel5.add(m_jButtonCancel);

        getContentPane().add(jPanel5, java.awt.BorderLayout.SOUTH);

        jButton1.setEnabled(false);
		m_jButtonOK.setEnabled(false);	
		
		jhostCob.setModel(new DefaultComboBoxModel());
        jhostCob.addItemListener(new ItemListener(){
        	public void itemStateChanged(ItemEvent e) { 
        		   if (e.getStateChange() == ItemEvent.SELECTED) {
        			   editor.hostSelected((T) e.getItem());
        		   }
        		}
        }); 
    }// </editor-fold>//GEN-END:initComponents

    private void m_jButtonOKActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_m_jButtonOKActionPerformed
        boolean closeAble=true;
        if(dirty.isDirty()){
            try {
                retObj = editor.createValue();
                if(dlSales!=null&&editor.getState()==AbstractDAOJEditor.STATE_Insert){
                    dlSales.insert((I_BaseBean)retObj);
                    cobeModel.addElement(retObj);
                }else if(dlSales!=null&&editor.getState()==AbstractDAOJEditor.STATE_Edit)
                    dlSales.update((I_BaseBean)retObj);
                dirty.setDirty(false);
            } catch (BasicException ex) {
                JMessageDialog.showMessage(JEditorWarpDialog.this, new MessageInf(ex));
                closeAble=false;
            }
        }
      if(closeAble)
          dispose();
}//GEN-LAST:event_m_jButtonOKActionPerformed

    private void m_jButtonCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_m_jButtonCancelActionPerformed
        dirty.setDirty(false);
        retObj=null;
        dispose();
}//GEN-LAST:event_m_jButtonCancelActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
       if(dirty.isDirty()){
            try {
                retObj = editor.createValue();
                if(editor.getState()==AbstractDAOJEditor.STATE_Insert){
                    dlSales.insert((I_BaseBean)retObj);
                    cobeModel.addElement(retObj);
                }
                else if(editor.getState()==AbstractDAOJEditor.STATE_Edit)
                    dlSales.update((I_BaseBean)retObj);
                dirty.setDirty(false);
                editor.writeValueEdit(retObj);
            } catch (BasicException ex) {
                JMessageDialog.showMessage(JEditorWarpDialog.this, new MessageInf(ex));
            }
        }
    }//GEN-LAST:event_jButton1ActionPerformed

    public T getRetObj() {
        return retObj;
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JPanel jPanel5;
    private javax.swing.JButton m_jButtonCancel;
    private javax.swing.JButton m_jButtonOK;
    private JComboBox jhostCob;
    private JButton btnC;
    private JPanel extPanel;
    // End of variables declaration//GEN-END:variables

    public Component getComponent() {
        return this;
    }

    public void activate() throws BasicException {
    	editor.activate();
    }

	@Override
	public String getLogerString() {
		return editor.getLogerString();
	}

	@Override
	public boolean isLogAble() {
		return  editor.isLogAble();
	}
	
}
